const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const pool = require('../config/database');
const { AppError } = require('../utils/errorHandler');
const { StatusCodes } = require('http-status-codes');

class UserController {
  async login(req, res, next) {
    try {
      const { username, password } = req.body;
      
      // 查询用户
      const [users] = await pool.query(
        'SELECT * FROM users WHERE username = ?',
        [username]
      );
      
      if (users.length === 0) {
        throw new AppError('用户名或密码错误', StatusCodes.UNAUTHORIZED);
      }

      const user = users[0];
      
      // 验证密码
      const isPasswordValid = await bcrypt.compare(password, user.password);
      if (!isPasswordValid) {
        throw new AppError('用户名或密码错误', StatusCodes.UNAUTHORIZED);
      }

      // 生成token
      const token = jwt.sign(
        { id: user.id, username: user.username, role: user.role },
        process.env.JWT_SECRET,
        { expiresIn: process.env.JWT_EXPIRES_IN }
      );

      res.json({
        status: 'success',
        token
      });
    } catch (error) {
      next(error);
    }
  }

  async register(req, res, next) {
    try {
      const { username, password, role } = req.body;
      
      // 检查用户名是否已存在
      const [existingUsers] = await pool.query(
        'SELECT * FROM users WHERE username = ?',
        [username]
      );
      
      if (existingUsers.length > 0) {
        throw new AppError('用户名已存在', StatusCodes.BAD_REQUEST);
      }

      // 加密密码
      const hashedPassword = await bcrypt.hash(password, 10);

      // 创建用户
      const [result] = await pool.query(
        'INSERT INTO users (username, password, role) VALUES (?, ?, ?)',
        [username, hashedPassword, role]
      );

      res.status(StatusCodes.CREATED).json({
        status: 'success',
        data: {
          id: result.insertId,
          username
        }
      });
    } catch (error) {
      next(error);
    }
  }
}

module.exports = new UserController();
